#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "global.h"
#include "server_global.h"
#include "dp_config.h"

/* Init variables.
 * Add vars in here, don't be forgot add same into server_global.h.
 * Add vars into dp_long_options. */

char *dp_version;
char *server_name;
char *datadir;
char *basedir;
char *logdir;
char *dpfile;

uint32 table_partitions;
uint32 max_databases;
uint32 max_tables;
uint32 max_table_partitions;

struct my_option dp_long_options[] = {
    {"version", 0,
        "The server start server name.",
        &dp_version,
        &dp_version,
        0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"server_name", 0,
        "The server start server name.",
        &server_name,
        &server_name,
        0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"basedir", 0,
        "The server installation location.",
        &basedir,
        &basedir,
        0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"datadir", 0,
        "Table defintion & database definition.",
        &datadir,
        &datadir,
        0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"segment_number", 0,
        "table_partitions per table",
        &table_partitions,
        &table_partitions,
        0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"max_databases", 0,
        "max number of databases",
        &max_databases,
        &max_databases,
        0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"max_tables", 0,
        "max number of tables",
        &max_tables,
        &max_tables,
        0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
    {"max_segments", 0,
        "max number of partitions per table",
        &max_table_partitions,
        &max_table_partitions,
        0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0}
};

static
int
read_dpfile(
    char *buf)
{
    int fd;
    uint len;

    if ((fd = open(dpfile, O_RDONLY)) < 0)
    {
        fprintf(stderr, "Can't open '%s'\n", dpfile);
        return 1;
    }
    len = read(fd, buf, MAX_BUF);
    close(fd);
    if (0 == len)
        return 1;

    return 0;
}

int load_dpfile(void)
{
    uint32 res = 0;
    char buf[MAX_BUF];
    res = read_dpfile(buf);
    if (!res)
        printf("%s\n", buf);
    return res;
}
/* END FILE */
